
import * as fun from "../../core/fun.js";
import * as bfun from '../../core/fbyte.js';
import * as fdate from "../../core/fdate.js";
/**
 * 好运来专用底层标准消息包
 */
export default class Msgpg {	
	constructor(发送方, 接收方, 主题, 字符串, 字节串, 时间) {
		// 0 系统消息 1用户消息 2 用户指令
		this.set发送方(发送方); // null
		this.setMsg(主题, 字符串, 字节串, 时间, 接收方)
		this.包数据长度 = 0;
	}
	set发送方(发送方) {
		if (fun._IS.isEmptyString(发送方)) {
			this.发送方 = null;
			this.类型 = 0;
		} else {
			this.发送方 = 发送方;
			this.类型 = 1;
		}
	}
	set接收方(接收方) {
		this.接收方 = 接收方;
	}

	setMsg(接收方,主题, 字符串, 字节串, 时间) {
		if (接收方)
			this.接收方 = 接收方;
		this.主题 = 主题;
		this.字符串 = 字符串;
		this.字节串 = 字节串;
		this.时间 = fdate.getNow(时间);
	}

	/**
	 * 返回编译的字节
	 * 
	 * @return
	 */
	toSendBytes() {
		let i = new Array();
		let b0 = this.类型;
		let b1 = bfun.strToUtf8Array(this.发送方);
		let b2 = bfun.strToUtf8Array(this.接收方);
		let b3 = bfun.strToUtf8Array(this.主题);
		let b4 = bfun.strToUtf8Array(this.字符串);
		let b5 = bfun.strToUtf8Array(this.时间);
		i[0] = (b1 == null ? 0 : b1.length);
		i[1] = (b2 == null ? 0 : b2.length);
		i[2] = (b3 == null ? 0 : b3.length);
		i[3] = (b4 == null ? 0 : b4.length);
		i[4] = (b5 == null ? 0 : b5.length);
		i[5] = (this.字节串 == null ? 0 : this.字节串.length);

		this.包数据长度 = 4 * 6 + 1 + i[0] + i[1] + i[2] + i[3] + i[4] + i[5]; // 除i[0]以外 剩余数据的长度
		return bfun.concatUi8Arr(bfun.intToUi8Arr(this.包数据长度), [b0], bfun.intToUi8Arr(i[0]), //
			bfun.intToUi8Arr(i[1]), bfun.intToUi8Arr(i[2]), //
			bfun.intToUi8Arr(i[3]), bfun.intToUi8Arr(i[4]), //
			b1, b2, b3, b4, b5, this.字节串);

	}

	/**
	 * 
	 * @param {Uint8Array}data
	 * @return 返回 false 表示未结束 true 表示结束了
	 */
	ini(data) {
		if (data == null || data.length == 0) {
			this.包数据长度 = 0;
			return false;
		}
		if (4 > data.length) {
			this.包数据长度 = 0;
			return false;
		}
		this.包数据长度 = bfun.byte4ToInt(data, 0);
		//console.log(this.包数据长度);
		if (this.包数据长度 > data.length) {
			this.包数据长度 = 0;
			return false;
		}
		let i = new Array();
		this.类型 = data[4];
		let start = 5;
		for (let j = 0; j < 5; j++) {
			i[j] = bfun.byte4ToInt(data, start);
			start += 4;
			//console.log(i[j],start);
		}
		this.发送方 = bfun.Utf8ArrayToStr(bfun.subBytes(data, start, i[0]));
		start += i[0];
		this.接收方 = bfun.Utf8ArrayToStr(bfun.subBytes(data, start, i[1]));
		start += i[1];
		this.主题 = bfun.Utf8ArrayToStr(bfun.subBytes(data, start, i[2]));
		start += i[2];
		this.字符串 = bfun.Utf8ArrayToStr(bfun.subBytes(data, start, i[3]));
		start += i[3];
		this.时间 = bfun.Utf8ArrayToStr(bfun.subBytes(data, start, i[4]));
		start += i[4];
		let i5 = this.包数据长度 - start;
		this.字节串 = bfun.subBytes(data, start, i5);
		//slice 区别于subarray ,slice 截取后并重新创建一个 ,subarray 只是一个截取窗口	
		return 	data.length> this.包数据长度;
	}

	/**
	 * 包数据=包头(4字节)+包长度
	 * 
	 * @return
	 */
	length() {
		return this.包数据长度;
	}
	
	
}



Msgpg.prototype.DC系统消息 = 0;
Msgpg.prototype.DC用户消息 = 1;
